/**  
 * All rights Reserved, Designed By <a href="www.itttq.com" target="_blank">www.itttq.com</a>
 * @date:   2017-07-21 11:42:21
 * @Copyright: 2017 <a href="www.itttq.com" target="_blank">www.itttq.com</a> Inc. All rights reserved. 
 */
package com.itttq.gshop.pbpm.service;

import java.security.NoSuchAlgorithmException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.itttq.gshop.domain.po.SysUserPo;
import com.itttq.gshop.domain.to.ResultPageTo;
import com.itttq.gshop.generic.util.Constants;
import com.itttq.gshop.generic.util.EncryptUtil;
import com.itttq.gshop.pbpm.mapper.ISysUserMapper;

@Service
public class SysUserService {
	@Autowired
	private ISysUserMapper sysUserMapper;
	
	/**
	 * 根据ID获取SysUserPo对象
	 * 
	 * @param id
	 * @return
	 * @Author 迷蝶
	 * @return SysUserPo
	 */
	public SysUserPo getSysUser(int id) {
		return sysUserMapper.findSysUserById(id);
	}
	
	/**
	 * 根据条件获取SysUserPo对象，并返回查询的数据总数
	 * 
	 * @param sysUser
	 * @Author 迷蝶
	 * @return ResultPageTo<SysUserPo>
	 */
	public ResultPageTo<SysUserPo> getSysUsers(SysUserPo sysUser) {
		return new ResultPageTo<SysUserPo>(sysUser.getStart(), sysUser.getSize(), 
				sysUserMapper.findSysUserCount(sysUser), sysUserMapper.findSysUsers(sysUser));
	}
	
	/**
	 * 根据ID删除SysUserPo对象
	 * 
	 * @param id
	 * @Author 迷蝶
	 */
	public Integer delSysUser(int id) {
		return sysUserMapper.delSysUserById(id);
	}
	
	/**
	 * 用户登录
	 * 
	 * @param username	用户名
	 * @param password	密码
	 * @return
	 * @Author 迷蝶
	 * @return SysUserPo	为null表示用户名或密码错误
	 */
	public SysUserPo login(String username, String password) {
		SysUserPo sysUser = new SysUserPo();
		sysUser.setUsername(username);
		List<SysUserPo> users = sysUserMapper.findSysUsers(sysUser);
		if(null == users || users.isEmpty()) {
			sysUser = null;
		} else {
			sysUser = users.get(0);
			try {
				if(!sysUser.getPassword().equals(EncryptUtil.getPassword(password, sysUser.getSalt()))) {
					sysUser = null;
				}
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
				sysUser = null;
			}
		}
		return sysUser;
	}
	
	/**
	 * 增加SysUserPo对象
	 * 
	 * @param sysUser
	 * @Author 迷蝶
	 */
	public Integer addSysUser(SysUserPo sysUser) {
		try {
			// 生成盐值和密码
			String salt = Constants.genRandomChar(6);
			sysUser.setSalt(salt);
			sysUser.setPassword(EncryptUtil.getPassword(sysUser.getPassword(), salt));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return sysUserMapper.addSysUser(sysUser);
	}
	
	/**
	 * 根据条件更新SysUserPo对象
	 * 
	 * @param sysUser
	 * @Author 迷蝶
	 */
	public Integer updateSysUser(SysUserPo sysUser) {
		return sysUserMapper.updateSysUser(sysUser);
	}
	
}
